package com.jcli.fx3u;

import com.jcli.HslCommunication.Core.Types.OperateResult;
import com.jcli.HslCommunication.Profinet.Melsec.MelsecA1ENet;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;

/**
 实现了plc的数据读取。启动，停止，默认启动。
 */
public class _03_PLCDataReaderGUI extends JFrame {
    private JTextArea textArea;
    private JButton startButton;
    private JButton stopButton;
    private boolean isReading = false;
    private MelsecA1ENet melsec_net;

    public _03_PLCDataReaderGUI() {
        setTitle("PLC数据读取器");
        setSize(400, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel panel = new JPanel(new BorderLayout());

        textArea = new JTextArea();
        JScrollPane scrollPane = new JScrollPane(textArea);
        panel.add(scrollPane, BorderLayout.CENTER);

        JPanel buttonPanel = new JPanel();
        startButton = new JButton("启动");
        stopButton = new JButton("停止");
        stopButton.setEnabled(false); // 初始状态下停止按钮禁用
        buttonPanel.add(startButton);
        buttonPanel.add(stopButton);
        panel.add(buttonPanel, BorderLayout.SOUTH);

        add(panel);

        startButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (!isReading) {
                    startReading();
                }
            }
        });

        stopButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                stopReading();
            }
        });
    }

    private void startReading() {
        isReading = true;
        melsec_net = new MelsecA1ENet("192.168.1.11", 3000);
        melsec_net.SetPersistentConnection();

        Thread readThread = new Thread(new Runnable() {
            @Override
            public void run() {
                startButton.setEnabled(false); // 启用读取时禁用启动按钮
                stopButton.setEnabled(true); // 启用读取时启用停止按钮

                while (isReading) {
                    readFromPLC();
                    try {
                        Thread.sleep(1000); // 读取间隔，可以根据需要调整
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                melsec_net.ConnectClose();
                startButton.setEnabled(true); // 停止读取后重新启用启动按钮
                stopButton.setEnabled(false); // 停止读取后禁用停止按钮
                showInfoMessage("数据读取已停止。");
            }
        });

        readThread.start();
        showInfoMessage("数据读取已启动。");
    }

    private void stopReading() {
        isReading = false;
    }

    private void readFromPLC() {
        try {
            // 使用 melsec_net.ReadInt32 方法读取 D497 寄存器的值
            int d497Value = melsec_net.ReadInt32("D497").Content;

            if (d497Value == 1) {
                // 如果 D497 寄存器的值为 1，使用循环逐个读取 D500-D700 寄存器的值
                int[] d500ToD700Values = new int[201];
                for (int i = 0; i < d500ToD700Values.length; i++) {
                    int[] readResult = melsec_net.ReadInt32("D" + (500 + i), (short) 1).Content;
                    // 检查读取是否成功并且结果数组不为空
                    if (readResult != null && readResult.length > 0) {
                        d500ToD700Values[i] = readResult[0]; // 获取数组的第一个元素作为整数
                    } else {
                        // 处理读取失败的情况
                        // 可以抛出异常、记录日志或采取其他适当的操作
                    }
                }

                // 在文本区域中显示 D500-D700 寄存器的值
                textArea.append("D500-D700 Values: " + Arrays.toString(d500ToD700Values) + "\n");

                // 将 D497 寄存器的值改写为 0
                OperateResult writeResult = melsec_net.Write("D497", 0);
                if (writeResult.IsSuccess) {
                    showInfoMessage("D497 已设置为 0。");
                } else {
                    showErrorMessage("写入 D497 失败： " + writeResult.ToMessageShowString());
                }
            }
        } catch (Exception ex) {
            showErrorMessage("从PLC读取失败： " + ex.getMessage());
        }
    }
    private void showErrorMessage(String message) {
        JOptionPane.showMessageDialog(
                this,
                message,
                "信息",
                JOptionPane.INFORMATION_MESSAGE
        );
    }

    private void showInfoMessage(String message) {
        JOptionPane.showMessageDialog(
                this,
                message,
                "信息",
                JOptionPane.INFORMATION_MESSAGE
        );
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                _03_PLCDataReaderGUI gui = new _03_PLCDataReaderGUI();
                gui.setVisible(true);
            }
        });
    }
}
